package service

import (
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
	"ruoyi-go/utils"
	"sort"
)

var SysDictDataService = &sysDictDataService{}

type sysDictDataService struct {
}

func (service sysDictDataService) OrderByDictSortAsc(dictDataList []system.SysDictData) {
	sort.Sort(ByDictSort(dictDataList))
}

type ByDictSort []system.SysDictData

func (d ByDictSort) Len() int { return len(d) }

func (d ByDictSort) Swap(i, j int) { d[i], d[j] = d[j], d[i] }

// Less 正序
func (d ByDictSort) Less(i, j int) bool { return d[i].DictSort < d[j].DictSort }

func (service sysDictDataService) SelectDictDataByType(dictType string) []system.SysDictData {
	var dictData []system.SysDictData
	mysql.MysqlDb().Raw("select * from sys_dict_data where status = '0' and dict_type = ? order by dict_sort", dictType).Scan(&dictData)
	return dictData
}

// SelectDictDataList 分页查询
func (service sysDictDataService) SelectDictDataList(params tools.SearchTableDataParam, isPage bool) tools.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysDictData := params.Other.(system.SysDictData)
	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysDictData

	var db = mysql.MysqlDb().Model(&rows)

	var dictLabel = sysDictData.DictLabel
	if dictLabel != "" {
		db.Where("dict_label = ?", dictLabel)
	}
	var dictType = sysDictData.DictType
	if dictType != "" {
		db.Where("dict_type like concat('%', ?, '%')", dictType)
	}
	var status = sysDictData.Status
	if status != "" {
		db.Where("status = ?", status)
	}

	db.Order("dict_sort asc")

	if err := db.Count(&total).Error; err != nil {
		return tools.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	}

	if rows == nil {
		return tools.Fail()
	} else {
		return tools.Success(rows, total)
	}
}

func (service sysDictDataService) FindDictCodeById(dictCode string) system.SysDictData {
	var dictData system.SysDictData
	err := mysql.MysqlDb().Where("dict_code = ?", dictCode).First(&dictData).Error
	if err != nil {
		panic(err.Error())
	}
	return dictData
}

func (service sysDictDataService) SaveDictData(dictDataParam system.SysDictData) {
	isDefault := dictDataParam.IsDefault
	if isDefault == "" {
		dictDataParam.IsDefault = "N"
	}
	err := mysql.MysqlDb().Model(&system.SysDictData{}).Create(&dictDataParam).Error
	if err != nil {
		panic(err.Error())
	}
}

func (service sysDictDataService) EditDictData(dictDataParam system.SysDictData) {
	err := mysql.MysqlDb().Updates(&dictDataParam).Error
	if err != nil {
		panic(err.Error())
	}
}

func (service sysDictDataService) DeleteDictData(dictCodes string) {
	var ids = utils.Split(dictCodes)

	// 获取事务对象并保存
	tx := mysql.MysqlDb().Begin()
	if tx.Error != nil {
		panic(tx.Error.Error())
	}

	for i := 0; i < len(ids); i++ {
		id := ids[i]
		err := tx.Where("dict_code = ?", id).Delete(&system.SysDictData{}).Error
		if err != nil {
			tx.Rollback()
			panic(err.Error())
		}
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		panic(err.Error())
	}

	// 或者直接调用删除方法，不使用事务。上述使用事务是为了保证数据一致性。
	// err := mysql.MysqlDb().Where("dict_code in (?)", ids).Delete(&SysDictData{}).Error
	// if err != nil {
	// 	return R.ReturnFailMsg(err.Error())
	// }
}
